<template>
	<custom-form-layout>
		<fui-form ref="form">
			<custom-form-item-card>
				<fui-form-item label-width="auto" label="创建时间" :bottomBorder="false" asterisk highlight>
					<template #right>
						<fui-text :text="formData.createTime" type="primary"></fui-text>
					</template>
				</fui-form-item>
			</custom-form-item-card>



			<custom-form-item-card label="故障描述" required>
				<template #other>
					<fui-button @click="onSearch" btn-size="mini">
						查询
					</fui-button>
				</template>
				<!-- 	<mp-html ref="mpHtml" placeholder="请填写故障描述" :editable="editable"
					:content="faultRemarkContent"></mp-html> -->
				<fui-textarea :border-top="false" v-model="formData.faultRemark" maxlength="1000"></fui-textarea>


				<fui-form-item @click="choseFatulType" label-width="auto" label="故障分类" :bottomBorder="false" asterisk
					arrow highlight>
					<template #right>
						<fui-text :text="labelFaultType" type="primary"></fui-text>
					</template>
				</fui-form-item>
			</custom-form-item-card>

			<custom-form-item-card>
				<fui-form-item label-width="auto" label="录音">
					<custom-button-voice @change="changeVoice" :play-value="voiceFile"></custom-button-voice>

				</fui-form-item>
				<fui-form-item label-width="auto" label="附件" :bottomBorder="false">
					<view class="fui-flex__end">
						<custom-button-upload @change="changeUploadButton"></custom-button-upload>
					</view>
				</fui-form-item>
				<custom-file-list :list="fileList" @del="onDelFile"></custom-file-list>
			</custom-form-item-card>
			<!-- 	<custom-form-item-card required label="指派处理人">
				<fui-radio-group v-model="formData.sendType">
					<custom-form-item-cell label="派给科室" @click="choseDept" :placeholder="labelSendDept">
						<fui-radio value="3"></fui-radio>
					</custom-form-item-cell>
					<custom-form-item-cell label="派给小组/人" @click="choseTeamUser" :placeholder="labelSendTeamUser">
						<fui-radio value="2"></fui-radio>
					</custom-form-item-cell>
					<custom-form-item-cell :bottomBorder="false" :arrow="false" label="由我处理" placeholder="">
						<fui-radio value="1"></fui-radio>
					</custom-form-item-cell>
				</fui-radio-group>
			</custom-form-item-card> -->
			<custom-form-item-card label="备注">
				<fui-textarea v-model="formData.remarks" :border-top="false"></fui-textarea>
			</custom-form-item-card>

			<custom-form-item-card>

				<fui-form-item label-width="auto" label="报修人">
					<template #right>
						{{userInfo.userName}}
					</template>
				</fui-form-item>
				<fui-form-item label-width="auto" label="报修电话">
					<template #right>
						{{userInfo.phonenumber}}
					</template>
				</fui-form-item>


				<fui-form-item @click="choseReportDept" label-width="auto" label="报修科室" asterisk arrow highlight>
					<template #right>
						<fui-text :text="labelReportDept" type="primary"></fui-text>
					</template>
				</fui-form-item>
				<!-- 	<custom-form-item-cell label="报修科室" @click="choseReportDept" :placeholder="labelReportDept">

				</custom-form-item-cell> -->

				<fui-form-item label-width="auto" label="报修地址">
					<template #right>
						{{formData.place}}
					</template>
				</fui-form-item>
				<fui-form-item label-width="auto" label="故障地址">

					<fui-input v-model="formData.faultAddress" textRight :padding="['0','16rpx']" :borderBottom="false"
						placeholder="请输入" maxlength="255"></fui-input>
				</fui-form-item>
				<fui-form-item @click="choseIp" label-width="auto" label="报修IP" asterisk arrow highlight>
					<template #right>
						<fui-text :text="'请选择'" type="primary"></fui-text>
					</template>
				</fui-form-item>
				<!-- 		<custom-form-item-cell :bottomBorder="false" label="报修IP" @click="choseIp"
					placeholder="请选择"></custom-form-item-cell> -->

				<fui-list-cell v-for="item in IpPerviewList">
					{{item.text}}
				</fui-list-cell>

			</custom-form-item-card>

			<custom-form-item-card>
				<fui-form-item label-width="auto" label="紧急程度">
					<template #vertical>
						<view class="vertical">
							<custom-dic-select-tag :dicKey="DIC_KEY.obs_fault_degree"
								v-model="formData.degree"></custom-dic-select-tag>

						</view>

					</template>
				</fui-form-item>
				<fui-form-item label-width="auto" label="影响范围">
					<template #vertical>
						<view class="vertical">
							<custom-dic-select-tag :dicKey="DIC_KEY.obs_fault_range"
								v-model="formData.rangeType"></custom-dic-select-tag>

						</view>
					</template>
				</fui-form-item>
				<!-- <fui-form-item label-width="auto" label="响应类型">
					<template #vertical>
						<fui-radio-group v-model="formData.responseType">

							<custom-form-item-cell label="即刻处理" placeholder="">
								<fui-radio value="1"></fui-radio>
							</custom-form-item-cell>
							<custom-form-item-cell :bottomBorder="false" label="预约处理"
								:placeholder="formData.appointment || '预约处理时间'" @click="choseProcessingTime">
								<fui-radio value="2"></fui-radio>
							</custom-form-item-cell>

						</fui-radio-group>

					</template>
				</fui-form-item> -->
			</custom-form-item-card>

			<!-- 	<custom-form-item-card>
				<fui-form-item label-width="auto" label="预计工时" :bottomBorder="false">
					<fui-input :borderBottom="false" number type="number" textAlign="right" :padding="['0']"
						placeholder="请输入预计工时" maxlength="6" v-model="formData.reqTime"></fui-input>
					<template #right>
						<fui-text text="小时" type="primary"></fui-text>
					</template>
				</fui-form-item>
			</custom-form-item-card> -->

			<!-- <custom-form-item-card label="期望完成时间">
				<fui-radio-group v-model="formData.completeType">
					<custom-form-item-cell v-for="item in dicCompleteList" :label="item.dictLabel"
						:placeholder="item.dictValue ==='4'?'请选择':'' " :arrow="item.dictValue ==='4'?true:false "
						@click="choseCompleteTime">
						<fui-radio :value="item.dictValue"></fui-radio>
					</custom-form-item-cell>
				 
				</fui-radio-group>
			</custom-form-item-card> -->

			<!-- 	<custom-form-item-card>
				<fui-form-item label-width="auto" label="资产名称">
					<template #right>
						<fui-text text="apple"></fui-text>
					</template>
				</fui-form-item>
				<custom-form-item-cell label="资产位置" :placeholder="labelAssetAddr" :bottomBorder="false"
					@click="choseAddr">
				</custom-form-item-cell>
				<custom-form-item-cell label="实际报修地址" :placeholder="labelActualRepairPlace" :bottomBorder="false"
					@click="choseActualRepairPlace">
				</custom-form-item-cell>
			</custom-form-item-card> -->


			<fui-date-picker :show="createTimeDatePickerShow" type="3" @change="changeDatePicker"
				@cancel="cancelDatePicker"></fui-date-picker>

			<fui-date-picker :show="processingTimeShow" type="3" @change="changeProcessingTime"
				@cancel="cancelProcessingTime"></fui-date-picker>
			<fui-date-picker :show="completeTimeShow" type="3" @change="changeCompleteTime"
				@cancel="cancelCompleteTime"></fui-date-picker>
		</fui-form>
		<template #footer>
			<fui-row :gutter="32">
				<fui-col :span="6">
					<fui-button background="#F2F3FF" color="#0052D9" @click="cancel" :disabled="disabled">
						取消
					</fui-button>
				</fui-col>
				<fui-col :span="18">
					<fui-button @click="submit" :disabled="disabled">
						提交
					</fui-button>
				</fui-col>

			</fui-row>

		</template>
	</custom-form-layout>
	<fui-bottom-popup :show="showIp">
		<fui-checkbox-group v-model="formData.ipAddressId">
			<fui-label v-for="(item,index) in IpList" :key="index">
				<fui-list-cell>
					<view class="fui-align__center">
						<fui-checkbox isCheckMark checkMarkColor="#0052D9" :value="item.id" borderColor="#B2B2B2">
						</fui-checkbox>
						<text class="fui-text">{{item.text}}</text>
					</view>
				</fui-list-cell>
			</fui-label>
		</fui-checkbox-group>
		<fui-white-space size="mini" b background="#f1f1f1"></fui-white-space>
		<fui-row :gutter="18" style="padding: 18rpx;">
			<fui-col :span="12">
				<fui-button background="#F2F3FF" color="#0052D9" @click="addIp">
					添加IP
				</fui-button>
			</fui-col>
			<fui-col :span="12">
				<fui-button background="#0052D9" color="#fff" @click="cancelIp">确定</fui-button>
			</fui-col>
		</fui-row>

	</fui-bottom-popup>


	<fui-bottom-popup :show="showFaultRemark" @close="closePopup">
		<view class="fui-scroll__wrap">

			<fui-input label="故障描述" :modelValue="fr" @input="onFaultRemark" placeholder="故障描述"></fui-input>
			<scroll-view scroll-y class="fui-scroll__view">
				<fui-list-cell :highlight="false" v-for="(item,index) in FaultRemarkList" :key="index">
					<fui-text :text="item.title"></fui-text>
					<fui-button btn-size="mini" width="140rpx" height="64rpx" background="#0052D9" color="#fff"
						@click="quote(item)">引用</fui-button>
				</fui-list-cell>
			</scroll-view>
			<view class="fui-icon__close" @tap="closePopup">
				<fui-icon name="close" :size="48"></fui-icon>
			</view>
		</view>
	</fui-bottom-popup>

	<!-- <fui-date-picker :value="formData.createTime" :show="showCreateDatePicker" type="5" @change="changeCreateTime"
		@cancel="showCreateDatePicker = false"></fui-date-picker> -->

</template>

<script>
	import {
		mapState,
		mapWritableState,
		mapActions,
		mapGetters
	} from 'pinia'
	import utils from '@/components/firstui/fui-utils';
	import {
		DIC_KEY
	} from '../../config/dicKey-config';
	import {
		useDictStore
	} from '../../store/modules/dic';
	import {
		FormDeptStoreKey,
		FormDicStoreKey,
	} from '../../store/sotreKey';
	import {
		base64ToFile,
		DeptSelectChoseType,
		getCurrentPage,
		getDicValue,
		toDeptSelectPage,
		toDicSelectPage
	} from '../../utils/util';
	import {
		useDeptStore
	} from '../../store/modules/dept';
	import {
		ReportApi
	} from '../../api/report';
	import {
		useSyStemStore
	} from '../../store/modules/system';
	import _ from 'lodash'
	import {
		MainPages,
		SubPages
	} from '../../config/router-config';
	import {
		useReportStore
	} from '../../store/modules/report';
	import form from '@/components/firstui/fui-validator/fui-validator'
	import {
		WxApi
	} from '../../api/wx';

	import {
		FileApi
	} from '../../api/file';
	import {
		useAuthStore
	} from '../../store/modules/auth';
	import {
		useWx
	} from '../../store/modules/wx';
	import {
		keyDept
	} from '../../utils/handleDeptData';

	export default {
		name: "report",
		data() {
			return {
				DIC_KEY,
				createTimeDatePickerShow: false,
				processingTimeShow: false,
				completeTimeShow: false,

				showIp: false,
				editable: true,
				showFaultRemark: false,
				FaultRemarkList: [],
				fr: '',
				showCreateDatePicker: false,
				disabled: false,
			}
		},
		computed: {
			...mapState(useDictStore, ['dicStoreKey']),
			...mapState(useDeptStore, ['deptStoreKey']),
			...mapState(useSyStemStore, ['dicList']),
			...mapWritableState(useReportStore, ['formData', 'faultRemarkContent', 'fileList', 'IpList', 'voiceFile']),
			...mapGetters(useAuthStore, ['userInfo']),
			IpPerviewList() {
				return _.filter(this.IpList, (item) => {
					return this.formData.ipAddressId.includes(item.id)
				})
			},
			// dicCompleteList() {
			// 	return getDicValue(this.dicList, DIC_KEY.obs_complete_type)
			// },

			labelFaultType() {
				const {
					value
				} = this.dicStoreKey[FormDicStoreKey.ReportFaultType.key]
				if (value.length) {
					const v = JSON.parse(value[0])
					this.formData.faultType = v.value
					return v.label

				}
				this.formData.faultType = ''
				return '请选择'

				// return this.dicStoreKey[FormDicStoreKey.ReportFaultType.key].label
			},
			// labelSendDept() {
			// 	return this.deptStoreKey[FormDeptStoreKey.SendDept.key].label
			// },
			// labelSendTeamUser() {
			// 	return this.deptStoreKey[FormDeptStoreKey.SendDept.key].label
			// },
			labelReportDept() {
				const {
					value,
					label
				} = this.deptStoreKey[FormDeptStoreKey.ReportDept.key]
				if (value.length) {
					const v = _.map(value, item => JSON.parse(item))
					this.formData.deptId = v[0].value
					return v[0].label
				}

				return "请选择"
			},

			// 资产位置
			// labelAssetAddr() {
			// 	this.formData.equipmentAddressId = this.deptStoreKey[FormDeptStoreKey.ReportAssetAddr.key].value.split(
			// 		'-')[1]
			// 	this.formData.equipmentAddress = this.deptStoreKey[FormDeptStoreKey.ReportAssetAddr.key].label
			// 	return this.deptStoreKey[FormDeptStoreKey.ReportAssetAddr.key].label
			// },
			// 实际报修地址
			// labelActualRepairPlace() {
			// 	this.formData.actualRepairPlace = this.deptStoreKey[FormDeptStoreKey.ReportActualRepairPlace.key].value
			// 		.split('-')[1]
			// 	return this.deptStoreKey[FormDeptStoreKey.ReportActualRepairPlace.key].label
			// }
		},
		watch: {
			'formData.deptId': {
				handler: async function(val) {
					console.log(val, '00000000000');
					if (val) {
						const res = await ReportApi.getDeptDetail(val)
						this.formData.place = res.data.deptPlace || ''
						this.formData.ipAddressId = []
					}
				},
			}
		},
		mounted() {
			console.log('mount-dedddddd');
		},
		async onLoad(options) {
			console.log(options, 'options');
			this.injectSdk()
			if (options?.deptId) {
				try {
					const res = await ReportApi.getDeptDetail(options.deptId)
					// this.formData.deptId = options.deptId
					this.setStoreKeyValue([JSON.stringify({
						key: keyDept,
						label: res.data.deptName,
						value: res.data.deptId,
					})], '', FormDeptStoreKey.ReportDept.key)

				} catch (err) {
					console.log(err, 'sssssss');
					// this.fui.toast(err)
				}

			}
			this.formData.createTime = utils.dateFormatter(Date.now(), 'y-m-d h:i', 2)
		},
		onShow() {
			console.log('-----onShow-----');
			if (this.deptStoreKey[FormDeptStoreKey.SendDept.key].value) {
				const obj = this.deptStoreKey[FormDeptStoreKey.SendDept.key].value.split('-')
				this.formData.sendObjType = obj[0]
				this.formData.sendObjId = obj[1]
			}
			// if (this.deptStoreKey[FormDeptStoreKey.ReportDept.key].value) {
			// 	const obj = this.deptStoreKey[FormDeptStoreKey.ReportDept.key].value.split('-')
			// 	this.formData.deptId = obj[1]
			// }

		},
		beforeUnmount() {
			console.log('beforeDestroy', );
		},

		onHide() {},

		methods: {
			...mapActions(useReportStore, ['onDelFile']),
			...mapActions(useWx, ['injectSdk', 'wxHandle']),
			...mapActions(useDictStore, ['clearDicStoreKeyValue']),
			...mapActions(useDeptStore, ['clearDeptStoreKeyValue', 'setStoreKeyValue']),
			changeCreateTime(res) {
				this.formData.createTime = res.result
			},
			changeUploadButton(list) {

				this.fileList = [...this.fileList, ...list]
			},
			changeVoice(data) {
				this.voiceFile = data
			},
			quote(item) {
				this.formData.faultRemark = `问题描述:${item.title}\n症状:${item.question}\n`
				this.closePopup()
			},
			closePopup() {
				this.fr = '';
				this.showFaultRemark = false
			},

			onSearch() {
				this.showFaultRemark = true
			},
			// 输入故障分类描述
			onFaultRemark: _.debounce(async function(val) {
				// const content = this.$refs.mpHtml.getContent() 
				try {

					const res = await ReportApi.getKnowledgeList(val)
					this.FaultRemarkList = res.data
				} catch (err) {
					this.fui.toast(err)
					console.log(err);
				}
			}, 300),

			// 选择故障分类
			choseFatulType() {
				toDicSelectPage(FormDicStoreKey.ReportFaultType.key, DIC_KEY.obs_fault_type, false)
			},
			clickCreateTime() {
				this.createTimeDatePickerShow = true
			},
			changeDatePicker(e) {
				this.createTimeDatePickerShow = false
				console.log(e);
				this.result = JSON.stringify(e || {})
			},
			cancelDatePicker() {
				this.createTimeDatePickerShow = false
			},
			// 选择派单科室
			choseDept() {
				toDeptSelectPage(FormDeptStoreKey.SendDept.key, DeptSelectChoseType.selectDept, false)
			},
			// 选择小组人
			choseTeamUser() {
				toDeptSelectPage(FormDeptStoreKey.SendDept.key, DeptSelectChoseType.selectTeamUser, false)
			},
			// 选择报修科室
			choseReportDept() {
				toDeptSelectPage(FormDeptStoreKey.ReportDept.key, DeptSelectChoseType.selectDept, false)
			},
			//选择Ip
			async choseIp() {

				if (!this.formData.deptId) {
					uni.showToast({
						title: '未选择报修科室',
						icon: 'none'
					})
					return
				}
				// 100
				const res = await ReportApi.deptIdGetIpList(this.formData.deptId)
				const list = _.map(res.data, item => {
					return {
						text: item.ipAddress,
						color: '#181818',
						...item
					}
				})
				const ipList = list

				this.IpList = ipList
				this.showIp = true
			},
			// 选择预约处理时间
			choseProcessingTime() {
				this.processingTimeShow = true
			},

			changeProcessingTime(e) {
				this.processingTimeShow = false

				this.formData.appointment = e.result
			},
			cancelProcessingTime() {
				this.processingTimeShow = false
			},
			// 期望完成时间
			choseCompleteTime() {
				this.completeTimeShow = true
			},
			changeCompleteTime() {
				this.completeTimeShow = false
				this.formData.completeTime = e.result
			},
			cancelCompleteTime() {
				this.completeTimeShow = false
			},
			// 资产位置
			choseAddr() {
				toDeptSelectPage(FormDeptStoreKey.ReportAssetAddr.key, DeptSelectChoseType.selectDept, false)
			},
			// 实际报修地址
			choseActualRepairPlace() {
				toDeptSelectPage(FormDeptStoreKey.ReportActualRepairPlace.key, DeptSelectChoseType.selectDept, false)
			},
			// 取消选择
			cancelIp() {
				this.showIp = false
			},
			addIp() {
				const the = this
				uni.navigateTo({
					url: `${SubPages.ADD_IP.router}?backToPath=${getCurrentPage()}&deptId=${the.formData.deptId}&deptName=${the.labelReportDept}`
				})
			},
			uploadVoice() {
				const the = this
				return new Promise((reslove, reject) => {
					if (this.voiceFile) {
						this.wxHandle().uploadVoice({
							localId: this.voiceFile, // 需要上传的音频的本地ID，由stopRecord接口获得
							isShowProgressTips: 1, // 默认为1，显示进度提示
							success: async function(res) {
								const serverId = res.serverId; // 返回音频的服务器端ID 
								// the.formData.recording = await FileApi.upWechatVoice(serverId)

								try {
									const v = await FileApi.upWechatVoice(serverId)
									reslove(v.data)
								} catch (err) {
									console.log(err);
									reject(err)
								}

							}
						});
					} else {
						reslove(null)
					}
				})
			},
			async submit() {
				const the = this
				// this.formData.faultRemark = this.faultRemarkContent
				const rules = [{
					name: "createTime",
					rule: ["required"],
					msg: ["请选择创建时间"]
				}, {
					name: "faultRemark",
					rule: ["required"],
					msg: ["请输入故障描述"]
				}, {
					name: "faultType",
					rule: ["required"],
					msg: ["请选择故障分类"]
				}, {
					name: 'ipAddressId',
					rule: ["required"],
					msg: ["请选择报修IP"],
					validator: [{
						msg: '请选择报修IP',
						method(val) {
							if (val.length) {
								return true
							}
							return false
						}
					}]
				}];
				let {
					isPassed,
					errorMsg
				} = form.validator(this.formData, rules)
				if (isPassed) {
					this.disabled = true
					this.formData.recording = await this.uploadVoice()
					for (let i of this.fileList) {
						try {
							let f = base64ToFile(i.base64)
							const result = await FileApi.upload('image', f)
							const r = await FileApi.uploadWechatFile(result.mediaId)
							this.formData.enclosure.push(r.data)
						} catch (err) {
							console.error(err);
						}

					}
					try {
						this.formData.user = this.userInfo.userName
						this.formData.phone = this.userInfo.phonenumber
						await ReportApi.createWorkOrder(this.formData)
						uni.showModal({
							icon: 'success',
							title: "报修成功!",
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									useReportStore().$reset()
									the.clearDicStoreKeyValue(FormDicStoreKey.ReportFaultType.key)
									the.clearDeptStoreKeyValue(FormDeptStoreKey.ReportDept.key)
									uni.redirectTo({
										url: MainPages.Index.router
									})
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						})
					} catch (err) {

						console.error(err);
						uni.showModal({
							content: err,
							showCancel: false,
						})
					}
				} else {
					console.error(errorMsg);
					uni.showToast({
						icon: 'error',
						title: errorMsg
					})


				}

			},

			async cancel() {
				uni.redirectTo({
					url: MainPages.Index.router
				})
			}
		},
	}
</script>

<style lang="scss" scoped>
	.vertical {
		margin: 16rpx;
	}

	.fui-icon__close {
		position: absolute;
		top: 24rpx;
		right: 24rpx;
	}

	.fui-scroll__wrap {
		padding-top: 30rpx;
		position: relative;
	}

	.fui-scroll__view {
		width: 100%;
		height: 600rpx;
	}
</style>